package com.edais.util;

import java.io.*;
import java.nio.charset.Charset;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import org.apache.log4j.Logger;

/**
 * 文件工具类
 * 
 * @author gaojing
 * @date 2017-3-10 14:07
 * 
 */
public class FileUtil {

	private static final Logger logger = Logger.getLogger(FileUtil.class);

	/**
	 * 将String数据存为文件
	 */
	public static File getFileFromBytes(String conText,String path) {
		byte[] b=conText.getBytes();
		BufferedOutputStream stream = null;
		File file = null;
		try {
			file = new File(path);
			FileOutputStream fstream = new FileOutputStream(file);
			stream = new BufferedOutputStream(fstream);
			stream.write(b);
			stream.close();
			logger.info(file.getAbsolutePath() + "数据转文件成功");
		} catch (Exception e) {
			logger.error("数据转换失败",e);
		}
		return file;
	}

	/**
	 *将文件转换成成byte[]
	 * @param file
	 * @return
	 * @throws Exception
	 */
    public static byte[] getBytesFromFile(File file) throws Exception {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            byte[] b = new byte[fileInputStream.available()];
            fileInputStream.read(b);
            return b;
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
            } catch (IOException e) {
            }
        }

    }
    
    /**
	 *将byte[]写出到PDF文件
	 * @param savePath data
	 * @return
	 * @throws Exception
	 */
    public static void wirteDataToFile(String savePath,byte[] data ) throws Exception{
        FileOutputStream fileOutputStream=null;
        try {
            fileOutputStream = new FileOutputStream(savePath);
            fileOutputStream.write(data);
            fileOutputStream.flush();
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
            }
        }
    }

	/**
	 * html 转换成pdf
	 * @param filePath
	 * @param pdfPath
	 * @return  pdfPath,htmlPath
	 * @throws Exception
	 */
	public static String htmlToPDF(String pdfPath,String filePath)throws Exception {
		String result ="";
		// step 1
		Document document = new Document();
		// step 2
		PdfWriter writer;
		try {

			writer = PdfWriter.getInstance(document, new FileOutputStream(pdfPath));
			// step 3
			document.open();
			// step 4
			String font = "/usr/share/fonts/";

			if ("win".equalsIgnoreCase(System.getProperties().getProperty("os.name").substring(0, 3))) {
				font = "C:/Windows/Fonts";
			}
			// step 4
			XMLWorkerHelper.getInstance().parseXHtml(writer, document,
					new FileInputStream(filePath), Charset.forName("UTF-8"),
					new XMLWorkerFontProvider(font));
			result = pdfPath;

		} catch (FileNotFoundException e) {
			logger.error("文件不存在！" , e);
		} catch (DocumentException e) {
			logger.error("转换失败！:" , e);
		} finally {
			// step 5
			document.close();
			return result;
		}
	}

	/**
	 * 删除某个文件夹下的所有文件夹和文件
	 * 
	 * @param delpath
	 * @throws Exception
	 * @return boolean
	 */
	public static boolean deletefile(String delpath) throws Exception {
		try {

			File file = new File(delpath);
			// 当且仅当此抽象路径名表示的文件存在且 是一个目录时，返回 true
			if (!file.isDirectory()) {
				file.delete();
			} else if (file.isDirectory()) {
				String[] filelist = file.list();
				for (int i = 0; i < filelist.length; i++) {
					File delfile = new File(delpath + "\\" + filelist[i]);
					if (!delfile.isDirectory()) {
						delfile.delete();
					} else if (delfile.isDirectory()) {
						//递归删除文件夹下的文件
						deletefile(delpath + "\\" + filelist[i]);
					}
				}
			}
			logger.info( "成功删除" +file.getAbsolutePath() + "文件夹中的文件！！！");
		} catch (FileNotFoundException e) {
			logger.error("deletefile() Exception:" , e);
		}
		return true;
	}
	 
}
